package com.tom.happy.mrs.chicken.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;

import com.tom.happy.mrs.chicken.R;

public class CustomBg extends View {
    private Bitmap mBitmap = null;
    private Rect mSrcRect = new Rect();
    private Rect mDstRect = new Rect();

    public CustomBg(Context context) {
        this(context, null);
    }

    public CustomBg(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    private float distance = 0;

    @Override
    protected void onDraw(Canvas canvas) {
        int width = getMeasuredWidth();
        int height = getMeasuredHeight();
        if (mBitmap == null) {
            mBitmap = zoomImage(BitmapFactory.decodeResource(getResources(), R.drawable.bg_launch), width, height);
        }
        mSrcRect.set(0, 0, width, height);
        mSrcRect.set(0, 10, width, height);
//        canvas.save();
        //canvas.translate(0, distance += 10);
        canvas.rotate(30);
//        canvas.drawBitmap(mBitmap, mSrcRect, mDstRect, null);
//        canvas.restore();
//        invalidate();

        canvas.drawBitmap(mBitmap, mSrcRect, mDstRect, null);
        invalidate();
    }

    public static Bitmap zoomImage(Bitmap bgimage, double newWidth,
                                   double newHeight) {
        // 获取这个图片的宽和高
        float width = bgimage.getWidth();
        float height = bgimage.getHeight();
        // 创建操作图片用的matrix对象
        Matrix matrix = new Matrix();
        // 计算宽高缩放率
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // 缩放图片动作
        matrix.postScale(scaleWidth, scaleHeight);
        Bitmap bitmap = Bitmap.createBitmap(bgimage, 0, 0, (int) width,
                (int) height, matrix, true);
        return bitmap;
    }
}
